<template>
  <el-scrollbar>
    <el-form
      ref="formRef"
      :validate-on-rule-change="false"
      class="flex flex-col items-start gap-y-4"
      label-position="top"
      :model="formState"
      :rules="rules"
      require-asterisk-position="right"
    >
      <quote-card class="pt-0">
        <domain-input v-model="formState.domains" />
        <el-form-item class="mb-8" prop="conditions">
          <template #label>
            <el-radio v-model="delType" :label="1"
              >删除满足右侧条件的记录</el-radio
            >
          </template>
          <div class="flex flex-col">
            <div
              v-for="(item, index) in moreInputs"
              :key="index"
              class="flex m-input"
            >
              <el-input
                v-model="item.value"
                :disabled="delDisabled"
                placeholder="请输入"
                class="w-[400px]"
              >
                <template #prepend>
                  <el-select v-model="item.key" class="w-[140px]">
                    <el-option label="主机记录等于" value="name" />
                    <el-option label="记录值等于" value="value" />
                  </el-select>
                </template>
              </el-input>
              <div class="ml-4">
                <el-button
                  v-if="!(moreInputs.length === 1 && index === 0)"
                  :disabled="delDisabled"
                  :icon="Minus"
                  @click="moreInputs.splice(index, 1)"
                />
                <el-button
                  v-if="index === moreInputs.length - 1"
                  :disabled="delDisabled"
                  :icon="Plus"
                  @click="moreInputs.splice(index + 1, 0, initMoreItem())"
                />
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="formState.operator"
            :disabled="delDisabled"
            class="w-[400px]"
          >
            <el-option value="OR" label="满足任意一个条件" />
            <el-option value="AND" label="满足以上所有条件" />
          </el-select>
        </el-form-item>
        <el-form-item :label-width="0">
          <el-radio v-model="delType" :label="2"
            >删除域名内（含子域名）的所有解析记录</el-radio
          >
        </el-form-item>
        <!-- <div class="pt-[14px]">
          <el-divider class="m-0" />
          <el-button
            type="primary"
            :disabled="!formState.domains"
            :loading="loading"
            class="w-[74px] mb-2 mt-4"
            @click="handleSubmit"
            >删除</el-button
          >
        </div> -->
      </quote-card>
      <delete-log-error-dialog
        v-model:visible="errorDialogVisible"
        :state="errorState"
      />
    </el-form>
  </el-scrollbar>
</template>

<script setup lang="ts">
import { Minus, Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import type { Ref } from 'vue'

import type { UserModel } from '@/apis/model/user'

import DomainInput from '../components/DomainInput.vue'
import DeleteLogErrorDialog from '../dialogs/batch/DeleteLogErrorDialog.vue'
import type { IBatchActive, SubmitBtnUpdateFn } from '../type'
import { SUBMIT_BTN_UPDATE } from '../utils/constants'
import { useRules } from '../utils/rules/batchDeleteLog'

type EditType = 'name' | 'value'
type MoreItem = { key: EditType; value: string }

const formRef = ref<FormInstance>()

const initMoreItem = (): MoreItem => ({ key: 'name', value: '' })
const moreInputs = ref([initMoreItem()])

const formState = reactive({
  domains: '',
  group_id: '',
  operator: 'AND' as 'AND' | 'OR',
  expr: { key: 'name', value: '' },
  conditions: computed(() => (delType.value === 1 ? moreInputs.value : void 0))
})

const delType = ref(1)

const errorDialogVisible = ref(false)

const updateSubmitBtn = inject(SUBMIT_BTN_UPDATE) as SubmitBtnUpdateFn
const active = inject('active') as Ref<IBatchActive>

watchEffect(() => {
  if (active.value === '批量删除记录') {
    updateSubmitBtn({ onSubmit: handleSubmit })
  }
})

watchEffect(() => {
  updateSubmitBtn({ disabled: !formState.domains })
})

const errorState = reactive({
  success_count: '0',
  domain_count: '0',
  fail_domains: [] as string[]
})

const domains = computed(() => getTrimValue(formState.domains))

const user = inject('user') as Ref<UserModel>

const delDisabled = computed(() => delType.value === 2)

const rules = useRules(delDisabled)

const loading = ref(false)
watch(loading, val => updateSubmitBtn({ loading: val }))

async function handleSubmit() {
  await formRef.value?.validate()
  loading.value = true
  const conditions = formState.conditions?.filter(v => v.value)

  try {
    const res = await deleteBatchRecordApi({
      user_id: user.value.id!,
      conditions,
      domains: domains.value,
      operator: delType.value === 1 ? formState.operator : void 0
    })

    if (!res.fail_domains?.length) {
      return ToastUtils.success(
        `<div class="pb-1">删除成功</div>
          <div>共删除${res.success_count}条记录</div>`
      )
    } else {
      errorState.domain_count = res.domain_count ?? '0'
      errorState.success_count = res.success_count ?? '0'
      errorState.fail_domains = res.fail_domains ?? []
      errorDialogVisible.value = true
    }
  } finally {
    loading.value = false
  }
}

watch(delType, val => {
  val === 2 && formRef.value?.clearValidate('conditions')
})
</script>

<style lang="scss" scoped>
.m-input {
  & + .m-input {
    margin-top: 10px;
  }
}

.quote-card.el-card {
  :deep(.el-card__header) {
    padding: 0;
    margin-bottom: 0;
  }
}
</style>
